const fs = require("fs");
const path = require("path");
const { defineConfig } = require("@vue/cli-service");
const isDevelopment = process.env.NODE_ENV === "development";

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

console.log(process.env.npm_lifecycle_event);

let cookie;
let target;
if (isDevelopment) {
  let result = parseCookie();
  cookie = result.cookie;
  target = result.target;
}

let onlyMicroComponent = false;
//编译微组件
if (process.env.npm_lifecycle_event === "build:mc") {
  onlyMicroComponent = true;
}

const pages = getPages(isDevelopment, onlyMicroComponent);

console.table(pages);
console.log('target',target);
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
  productionSourceMap: false,
  outputDir: onlyMicroComponent ? "libCos" : "lib",
  assetsDir: isDevelopment ? "dev" : "",
  publicPath: isDevelopment
    ? '/'
    : '//dev-cdn-1251748120.file.myqcloud.com/static/files',
  pages,
  css: {
    extract: {
      filename: "[name]/style.css",
    },
  },
  filenameHashing: false,
  devServer: {
    proxy: {
      "(?!/dev^).*$": {
        target,
        changeOrigin: true,
        ws: false,
        onProxyReq(proxyReq) {
          proxyReq.setHeader("cookie", cookie);
          proxyReq.setHeader(
            "x-forwarded-host",
            target.includes("https://")
              ? target.substr("https://".length)
              : target.substr("http://".length)
          );
          proxyReq.setHeader(
            "x-forwarded-port",
            target.includes("https://") ? "443" : "80"
          );
        },
      },
    },
  },
  configureWebpack: (config) => {
    if (process.env.ANALYZE) {
      config.plugins.push(new BundleAnalyzerPlugin({
        analyzerPort: 3121
      }));
    }
    config.output.libraryTarget = "umd";
    config.output.filename = "[name]/index.js";
    config.output.libraryExport = "default";
    config.output.library = '[name]';
    if (!isDevelopment) {
      config.externals = [
        {
          vue: {
            root: "Vue",
            commonjs: "vue",
            commonjs2: "vue",
            amd: "vue",
          },
        },
      ];
    }
  },
  chainWebpack: (config) => {
    if (!process.env.ANALYZE) {
      config.optimization.delete("splitChunks");
    }
    if (!isDevelopment) {
      // config.optimization.delete("splitChunks");
      config.plugins.delete("copy");
      config.plugins.delete("preload");
      config.plugins.delete("prefetch");
      config.plugins.delete("html");
      config.entryPoints.delete("app");
    }
  },
});

/**
 * 获取需要编译入口文件
 * @param {boolean} isDevelopment 是否本地调试模式
 * @param {boolean} onlyMicroComponent 是否只获取微组件编译入口
 * @returns 需要编译的入口文件路径
 */
function getPages(isDevelopment, onlyMicroComponent = false) {
  if (isDevelopment) {
    return {
      index: "examples/b-goods-info-card/index.js",
    };
  } else {
    const PACKAGES_PATH = "src";
    const pages = {};
    fs.readdirSync(PACKAGES_PATH).forEach((dir) => {
      console.log(dir);
      if(dir!=='components') {
        const metaContent = fs.readFileSync(
            path.join(PACKAGES_PATH, dir, "meta.json")
        );
        const meta = JSON.parse(metaContent);

        //获取微组件入口文件
        if (onlyMicroComponent) {
          if (meta.micro_component) {
            pages[dir] = path.join(PACKAGES_PATH, dir, "index.js");
          }
        } else {
            pages[dir] = path.join(PACKAGES_PATH, dir, "index.js");
        }
      }
    });
    return pages;
  }
}

function parseCookie() {
  const COOKIE_PATH = "cookie.txt";
  if (!fs.existsSync(COOKIE_PATH)) {
    console.error("cookie.txt文件不存在");
    return {};
  }
  const content = fs.readFileSync(COOKIE_PATH).toString();

  const list = content.match(/(\w+)=(\w+)/g);
  const cookie = list
    .filter((item) =>
      /pc_user_key|ko_token|b_user_token|with_app_id/.test(item)
    )
    .join(";");

  let url;
  if (content.includes("sa_jssdk_2015_")) {
    url = content.match(/sa_jssdk_2015_(\w+)=/)[1].replace(/_/g, ".");
  } else {
    console.error("代理B端需要手动设置target");
  }
  console.log('url',url);
  console.log('cookie',cookie);

  return {
    cookie,
    target: url ? `https://${url}` : null,
    // cookie:'4700c160aa5437db88d966ffa3b12e19',
    // target:'https://publicizing-t.xiaoe-tech.com/'
  };
}
